package com.pylc.model.dao.impl;

import com.pylc.model.dao.AreaDao;
import com.pylc.model.entity.Area;
import org.apache.commons.lang.StringUtils;
import org.compass.core.util.CollectionUtils;
import org.hibernate.Hibernate;
import org.springframework.stereotype.Repository;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Lindsey
 */
@Repository
public class AreaDaoImpl extends BaseDaoImpl<Area, Long> implements AreaDao {

    public Set<Area> getRoot() {
        String hql = "from Area area where area.parent is null";
        return new HashSet<Area>((List<Area>) getHibernateTemplate().find(hql));
    }

    public Area getParent(Area area) {
        String hql = "from Area area join fetch area.parent where area.id = ?";
        List list = getHibernateTemplate().find(hql, area.getId());
        if (!CollectionUtils.isEmpty(list)) {
            area = (Area) list.get(0);
            return area.getParent();
        }
        return null;
    }

    public Set<Area> getChildren(Area area) {
        String hql = "from Area area join fetch area.children where area.id = ?";
        List list = getHibernateTemplate().find(hql, area.getId());
        if (!CollectionUtils.isEmpty(list)) {
            area = (Area) list.get(0);
            return area.getChildren();
        }
        return null;
    }

    public Boolean isNameUnique(Long parentId, String name) {
        String hql = "";
        List list = null;
        if (parentId == null) {
            hql = "from Area area where area.name = ? and area.parent is null";
            list = getHibernateTemplate().find(hql, name);
        } else {
            hql = "from Area area where area.name = ? and area.parent.id = ?";
            list = getHibernateTemplate().find(hql, new Object[] {name, parentId});
        }

        return list == null || list.size() == 0;
    }

}
